
package cn.edu.ctbu.sbadmin.system.api;

import cn.edu.ctbu.sbadmin.common.controller.BaseRestController;
import cn.edu.ctbu.sbadmin.common.domain.QueryPagePara;
import cn.edu.ctbu.sbadmin.common.utils.*;
import cn.edu.ctbu.sbadmin.system.domain.SysDictDO;
import cn.edu.ctbu.sbadmin.system.service.SysDictService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * @author Fromtech
 * @email tms@fromtech.net
 * @date 2018-11-19 15:45:15
 */
@RestController
@RequestMapping("/api/system/sysdict")
@Slf4j
@Api(value = "系统字典管理", tags = {"系统字典管理"})
public class SysDictRestController extends BaseRestController {
    @Autowired
    private SysDictService sysDictService;



    @RequestMapping("queryByType")
//    @RequiresPermissions("system:sysdict:list")
    public R queryByType(@RequestParam(value = "type", defaultValue = "") String type) throws Exception {
        QueryWrapper<SysDictDO> sysDictDOQueryWrapper = new QueryWrapper<SysDictDO>();
        sysDictDOQueryWrapper.eq("type", type);
        List<SysDictDO> list = sysDictService.list(sysDictDOQueryWrapper);
        return R.ok("data",list);
    }




    /**
     * 为select2准备的数据查询
     *
     * @param q
     * @return
     * @throws Exception
     */
    @RequestMapping("queryByQ")
    @RequiresPermissions("system:sysdict:list")
    public List<SysDictDO> queryByQ(@RequestParam(value = "q", defaultValue = "") String q) throws Exception {
        QueryWrapper<SysDictDO> sysDictDOQueryWrapper = new QueryWrapper<SysDictDO>();
        sysDictDOQueryWrapper.like("name", q);
        List<SysDictDO> list = sysDictService.list(sysDictDOQueryWrapper);
        return list;
    }

    /**
     * 根据 id取记录
     */
    @RequestMapping("/get")
    @RequiresPermissions("system:sysdict:list")
    public R get(Integer id) {
        SysDictDO config = sysDictService.getById(id);

        if (config != null) {
            return R.ok("data", config);
        }

        return R.error(-1, "出错了，找不到此数据!");
    }

    /**
     * 取所有记录
     */
    @RequestMapping("/getAll")
    @RequiresPermissions("system:sysdict:list")
    public R getAll() throws Exception {

        List<SysDictDO> sysDictList = sysDictService.getAll();

        return R.ok("data", sysDictList);
    }

    /**
     * 根据条件取所有记录
     */
    @RequestMapping("/getByPage")
    @RequiresPermissions("system:sysdict:list")
    public PageUtils list(@RequestParam("where") String where,
                          @RequestParam("pageSize") Integer pageSize,
                          @RequestParam("pageIndex") Integer pageIndex,
                          @RequestParam("sort") String sort,
                          @RequestParam("direct") String direct) throws Exception {
        //首先，把where条件的参数转为QueryAndItems
        //其中,where条件需要我们自己组装.示例:
        //name=张^:like&time=2^:lg&dmtCreate=2017-01-01^^2018-01-01
        //这个表示:
        //(name like '%张%' )and ( time<2 ) and (dmtCreate between '2017-01-01' and '2018-01-01)

        QueryPagePara mQuery = QueryParaHelper.GenQuery(where, pageSize, pageIndex, sort, direct);

        IPage<SysDictDO> sysDictList = sysDictService.getByPage(mQuery);




        PageUtils pageUtils = new PageUtils(sysDictList.getRecords(),
                sysDictList.getTotal());

        return pageUtils;
    }


    /**
     * 保存记录
     */
    @PostMapping("/save")
    @RequiresPermissions("system:sysdict:add")
    public R save(SysDictDO sysDictDO) {



        sysDictDO.setCreateDate(new Date());
        sysDictDO.setDelFlag(0);
        sysDictDO.setCreateBy(this.getUserId());
//        sysDictDO.set(getUser().getId());


        if (sysDictService.save(sysDictDO)) {
            return R.ok();
        }

        return R.error();
    }

    /**
     * 修改记录
     */
    @RequestMapping("/update")
    @RequiresPermissions("system:sysdict:edit")
    public R update(SysDictDO sysDictDO) {


        sysDictDO.setUpdateBy(this.getUserId());
        sysDictDO.setUpdateDate(new Date());
        sysDictService.updateById(sysDictDO);

        return R.ok();
    }


    /**
     * 逻辑删除记录
     */
    @PostMapping("/remove")
    @RequiresPermissions("system:sysdict:remove")
    public R remove(Integer id) {
        if (sysDictService.removeById(id)) {
            return R.ok();
        }

        return R.error();
    }


    /**
     * 逻辑删除
     */
    @PostMapping("/batchRemove")
    @RequiresPermissions("system:sysdict:remove")
    public R batchRemove(@RequestParam("ids[]") Long[] ids) {

        sysDictService.removeByIds(ids);

        return R.ok();
    }

    /**
     * 导出Excel
     *
     * @param response
     * @return
     * @throws Exception
     * @author
     */
    @RequestMapping(value = "exportExcel")
    @RequiresPermissions("system:sysdict:excel")
    public void exportExcel(
            @RequestParam("where") String where,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam("pageIndex") Integer pageIndex,
            @RequestParam("sort") String sort,
            @RequestParam("direct") String direct,
            HttpServletResponse response) throws Exception {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系

//        List<SysDictDO> sysDictDOS = sysDictService.getAll();

        QueryPagePara mQuery = QueryParaHelper.GenQuery(where, pageSize, pageIndex, sort, direct);

        IPage<SysDictDO> sysDictList = sysDictService.getByPage(mQuery);


        String fileName = URLEncoder.encode("字典表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SysDictDO.class).sheet("模板").doWrite(sysDictList.getRecords());

    }




}